var app = getApp();
var utils = require('../../utils/util.js');
var util = require('../../utils/shop/formatShop.js');
var WxParse = require('../../wxParse/wxParse.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab_switch: 0,  // 0：我的优惠券  1：领取优惠券   2：已过期/失效

    tab_act: {
      0: 'get_user_coupon',
      1: 'get_unaccalimed_coupon',
      2: 'get_expired_coupon'
    },

    list: [],
    post_data: {
      act: '',
      User_ID: 0,
      page: 1,
      pageSIzw: 20
    },
    get_flag: true,
    loading: true,

    layer_box_show: false,
    use_coupon_post: {
      coupon_id: 0,
      Price: '',
      Integral: '',
      Password: ''
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.tab_switch) {
      this.setData({
        tab_switch: options.tab_switch
      });
    }
    this.load();
  },

  // 页面加载
  load: function () {
    if (!app.globalData.userInfo) {
      app.login('', this.load);
      return false;
    }

    let tab_switch = this.data.tab_switch;
    let act = '';
    if (tab_switch == 0) {
      // 查询我的优惠券
      app.setNavBarTitle('我的优惠券');

    } else if (tab_switch == 1) {
      // 查询可领取优惠券
      app.setNavBarTitle('领取优惠券');

    } else if (tab_switch == 2) {
      // 查询失效的优惠券
      app.setNavBarTitle('已过期/失效');

    } else {
      wx.showModal({
        title: '提示',
        content: '参数错误',
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 1
          });
        }
      });
      return;
    }

    this.setData({
      'post_data.User_ID': app.globalData.userInfo.User_ID,
      'post_data.act': this.data.tab_act[tab_switch]
    });
    // 查询
    this.get_coupon();
  },

  // 查询优惠券
  get_coupon() {
    this.setData({
      loading: true
    });
    app.http_req(this.data.post_data, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        let list = res.data;
        for (let i in list) {
          let item = list[i];

          item.Coupon_EndTime = utils.format_time('yyyy-M-d h:mm:ss', item.Coupon_EndTime);
          WxParse.wxParse('detail[' + item.Coupon_ID + ']', 'html', item.Coupon_Description, this);
        }

        this.setData({
          list: res.totalCount > 0 ? this.data.list.concat(list) : [],
          'post_data.page': this.data.post_data.page + 1,
          get_flag: (res.totalCount / this.data.post_data.pageSize) > this.data.post_data.page ? true : false
        });
      } else {
        wx.showModal({
          title: '提示',
          content: typeof res.msg != 'undefined' ? res.msg : '查询失败',
          showCancel: false
        })
      }

      this.setData({
        loading: false
      });

      // 结束下拉刷新
      util.overPullDownRefresh();
    });
  },

  // tab切换
  nav_switch (e) {
    let tab_switch = e.currentTarget.dataset.switch_val;
    this.setData({
      tab_switch: tab_switch,
      list: [],
      'post_data.act': this.data.tab_act[tab_switch],
      'post_data.page': 1,
      get_flag: true,
      loading: true
    });
    this.get_coupon();
  },

  // 优惠券图片错误处理
  coupon_img_error (e) {
    let idx = e.currentTarget.dataset.idx;
    console.log(idx);
    this.setData({
      ['list[' + idx + '].Coupon_PhotoPath']: '/images/coupon.jpg'
    });
  },

  // 操作优惠券
  coupon_action (e) {
    let type = e.currentTarget.dataset.type;
    let coupon_id = e.currentTarget.dataset.coupon_id;
    if (type == 0) {  // 实体店消费
      this.setData({
        layer_box_show: true,
        'use_coupon_post.coupon_id': coupon_id
      });
    } else if (type == 1) { // 商城使用
      wx.switchTab({
        url: '/pages/index/index',
      });
    } else if (type == 2) { // 立即领取
      this.receive_coupon(coupon_id);
    }
  },

  // 领取优惠券
  receive_coupon(coupon_id) {
    let post_data = {
      act: 'user_receive_coupon',
      User_ID: app.globalData.userInfo.User_ID,
      coupon_id: coupon_id
    };
    app.http_req(post_data, app.globalData.init.api_url, 'POST', res => {
      if (res.errorCode == 0) {
        wx.showToast({
          title: res.msg,
          duration: 1000,
          success: function () {
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/coupon/coupon?tab_switch=0',
              });
            }, 1000);
          }
        });
      } else {
        wx.showModal({
          title: '提示',
          content: typeof res.msg != 'undefined' ? res.msg : '领取失败',
          showCancel: false
        });
      }
    });
  },

  // 弹窗关闭
  layer_box_close () {
    this.setData({
      layer_box_show: false,
      'use_coupon_post.coupon_id': 0,
      'use_coupon_post.Price': '',
      'use_coupon_post.Integral': '',
      'use_coupon_post.Password': '',
    });
  },

  // 实体店消费
  coupon_consumption(e) {
    let input = e.detail.value;
    if (!input.Price || input.Price <= 0) {
      wx.showToast({
        title: '请填写消费金额',
        icon: 'none'
      });
      return false;
    }

    if (!input.Password || input.Password == '') {
      wx.showToast({
        title: '请填写商家密码',
        icon: 'none'
      });
      return false;
    }

    let post_data = {
      act: 'use_coupon',
      User_ID: app.globalData.userInfo.User_ID,
      coupon_id: this.data.use_coupon_post.coupon_id,
      Price: input.Price,
      Integral: input.Integral && input.Integral > 0 ? input.Integral : 0,
      Password: input.Password
    };
    this.layer_box_close();
    wx.showLoading({
      title: '提交中...',
    });
    app.http_req(post_data, app.globalData.init.api_url, 'POST', res => {
      wx.hideLoading();
      if (res.errorCode == 0) {
        wx.showToast({
          title: res.msg,
          duration: 1000,
          success: () => {
            let list = this.data.list;
            for (let i in list) {
              let item = list[i];
              if (item.Coupon_ID == post_data.coupon_id) {
                item.Coupon_UsedTimes = res.data.Coupon_UsedTimes;
              }
              list[i] = item;
            }
            this.setData({
              list: list
            });
          }
        });
      } else {
        wx.showModal({
          title: '提示',
          content: typeof res.msg != 'undefined' ? res.msg : '使用失败',
          showCancel: false
        });
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //显示加载导航条
    wx.showNavigationBarLoading();
    //初始化数据 (防止数据重复)
    this.setData({
      list: [],
      'post_data.page': 1,
      get_flag: true,
      loading: true,
    });
    this.load();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.get_flag && !this.data.loading) {
      this.get_coupon();
    }
  }
})